package com.senke.aiagent.app;

import com.senke.aiagent.advisor.MyLoggerAdvisor;
import com.senke.aiagent.chatmemory.FileBasedChatMemory;
import com.senke.aiagent.constant.FileConstant;
import com.senke.aiagent.rag.LoveAppRagCustomAdvisorFactory;
import com.senke.aiagent.rag.MyQueryRewriter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.List;

@Component
@Slf4j
public class LoveApp {

    private final ChatClient chatClient;

    private static final String SYSTEM_PROMPT = "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。" +
            "围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；" +
            "恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。" +
            "引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。";

    @Resource
    private VectorStore loveAppVectorStore;

    @Resource
    private VectorStore pgVectorVectorStore;

    @Autowired
    private Advisor loveappRagCloudAdvisor;

    @Resource
    private MyQueryRewriter myQueryRewriter;

    @Resource
    private ToolCallback[] allTools;

    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    // 只存储数据的纪录类
    record LoveReport(String title, List<String> suggestions) {
    }

    public LoveApp(ChatModel dashscopeChatModel) {
        // 初始化基于内存的对话记忆
        //ChatMemory chatMemory = new InMemoryChatMemory();
        // 初始化基于文件的对话记忆
        String fileDir = FileConstant.FILE_SAVE_DIR + "/chat-memory";
        ChatMemory chatMemory = new FileBasedChatMemory(fileDir);
        // 初始化基于数据库的对话记忆，若开启，需要在参数中注入 loveReportMapper
        //ChatMemory chatMemory = new DatabaseChatMemory(loveReportMapper);
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory),
                        // 自定义日志 advisor
                        new MyLoggerAdvisor()
                        // 自定义 Re2 advisor
                        //new Re2Advisor()
                )
                .build();
    }

    /*
     * 进行对话
     */
    public String doChat(String message, String chatId) {
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                // 指定对话记忆 id 和对话记忆大小
                .advisors(spec -> spec.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        //log.info("content: {}", content);
        return content;
    }

    /*
     * 进行对话（流式输出）
     */
    public Flux<String> doChatByStream(String message, String chatId) {
        Flux<String> response = chatClient.prompt()
                .user(message)
                // 指定对话记忆 id 和对话记忆大小
                .advisors(spec -> spec.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .stream()
                .content();
        return response;
    }

    /*
     * 进行对话并生成恋爱报告
     */
    public LoveReport doChatWithReport(String message, String chatId) {
        LoveReport loveReport = chatClient.prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成恋爱结果，标题为{用户名}的恋爱报告，内容为建议列表")
                .user(message)
                // 指定对话记忆 id 和对话记忆大小
                .advisors(spec -> spec.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(LoveReport.class);
        //log.info("loveReport: {}", loveReport);
        return loveReport;
    }

    public String doChatWithRag(String message, String chatId) {
        // 查询重写
        message = myQueryRewriter.doQueryRewriter(message);
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 应用 RAG 知识库问答
                //.advisors(QuestionAnswerAdvisor.builder(loveAppVectorStore).build())
                /*.advisors(new QuestionAnswerAdvisor(
                        loveAppVectorStore,
                        SearchRequest
                                .builder()
                                .similarityThreshold(0.5)
                                .topK(3)
                                .build()))*/
                // 应用检索增强顾问（基于本地向量存储）
                .advisors(LoveAppRagCustomAdvisorFactory.createLoveAppRagCustomAdvisor(loveAppVectorStore))
                // 应用 RAG 增强检索服务（基于云知识库服务）
                //.advisors(loveappRagCloudAdvisor)
                // 应用 RAG 增强检索服务（基于 PgVector 向量存储）
                //.advisors(QuestionAnswerAdvisor.builder(pgVectorVectorStore).build())
                .call()
                .chatResponse();
        String response = chatResponse.getResult().getOutput().getText();
        //log.info("response: {}", response);
        return response;
    }

    /*
     * 进行对话（使用工具）
     */
    public String doChatWithTools(String message, String chatId) {
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                // 指定对话记忆 id 和对话记忆大小
                .advisors(spec -> spec.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .tools(allTools)
                // 工具上下文
                //.toolContext(Map.of("name", "shenke"))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        //log.info("content: {}", content);
        return content;
    }

    /*
     * 进行对话（使用 MCP 服务）
     */
    public String doChatWithMCP(String message, String chatId) {
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                // 指定对话记忆 id 和对话记忆大小
                .advisors(spec -> spec.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .tools(toolCallbackProvider)
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        //log.info("content: {}", content);
        return content;
    }
}
